package com.woniuxy.lab.woniu_lab.util;

import com.jcraft.jsch.*;
import com.woniuxy.lab.woniu_lab.exception.UserException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.Key;
import java.util.Date;
import java.util.Map;

import static com.woniuxy.lab.woniu_lab.exception.WebExceptionCode.TOKEN_IS_NULL;

/**
 * @author 17292
 */
@Slf4j
public class JwtUtil {
    public static final String LAP_USER_TOKEN = "lap-user-token";
    /**
     *  盐可以定义在springboot配置文件中，通过@ConfigurationProperties注解去读取
     */
    static String secret="qwertyuiopasdfghjklzxcvbnm!@#$%^&*()";


    /**
     * 1.用于创建令牌的方法
     */
    public static String getToken(Map claims, Integer day){
        Key key = Keys.hmacShaKeyFor(secret.getBytes());
        return Jwts.builder()
                //向payload中保存数据
            .setClaims(claims)
                //设置令牌的过期时间,令牌的过期时间一定要大于当前系统时间
            .setExpiration(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * day)))
                //加盐
            .signWith(key)
            .compact();
    }

    /**
     * 2.用于解析令牌的方法
     */

    public static Claims parseToken(String token){
        Key key = Keys.hmacShaKeyFor(secret.getBytes());
        return Jwts.parserBuilder()
                //使用指定的盐
                .setSigningKey(key)
                //创建解析令牌的对象
                .build()
                //解析令牌
                .parseClaimsJws(token)
                //获取载荷中保存的内容
                .getBody();
    }

    /**
     * 从令牌中获取用户id
     */
    public static Integer getUserIdFromReq(){
        // 获取token
        String token = getTokenFromReq();

        return (Integer) parseToken(token).get("userId");
    }

    /**
     * 从请求头中获取token
     */
    public static String getTokenFromReq(){

        HttpServletRequest request = WebUtil.getRequest();

        String token = request.getHeader(LAP_USER_TOKEN);

        if (token == null || token.isEmpty()) {
            throw new UserException(TOKEN_IS_NULL);
        }
        return token;
    }

    public static void rmToken(){
        HttpServletResponse response = WebUtil.getResponse();
        response.setHeader(LAP_USER_TOKEN,null);

    }
    /**
     *修改文件内容
     * @param filePath 修改文件的绝对路径
     * @param oldWord 修改前的内容
     * @param newWord 修改后的内容
     */
    public synchronized static void modifyFile(String filePath,String oldWord,String newWord){
        String host = "43.136.98.253";
        String username = "root";
        String password = "woniuCQ2023!@#$%^&*()";
//        String host = "192.168.70.95";
//        String username = "root";
//        String password = "123456";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            InputStream inputStream = channelSftp.get(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "", oldText = "";
            while ((line = reader.readLine()) != null) {
                oldText += line + "\n";
            }
            reader.close();

            String newText = oldText.replaceFirst(oldWord, newWord);

            OutputStream outputStream = channelSftp.put(filePath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(newText);
            writer.flush();
            writer.close();

            channelSftp.disconnect();
            session.disconnect();
        } catch (JSchException | SftpException | IOException e) {
            e.printStackTrace();
        }
    }
}
